package org.groupg.practice.http;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientExample {

    public static void main(String[] args) {
        try {
            sendGet();
            sendPost();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void sendGet() throws Exception {
        String url = "http://httpbin.org/get";
        HttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(url);
        HttpResponse response = client.execute(request);

        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
        String responseBody = EntityUtils.toString(response.getEntity());
        System.out.println(responseBody);
    }

    public static void sendPost() throws Exception {
        String url = "http://httpbin.org/post";
        HttpClient client = HttpClients.createDefault();
        HttpPost request = new HttpPost(url);
        StringEntity params = new StringEntity("param1=value1&param2=value2");
        request.addHeader("content-type", "application/x-www-form-urlencoded");
        request.setEntity(params);
        HttpResponse response = client.execute(request);

        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
        String responseBody = EntityUtils.toString(response.getEntity());
        System.out.println(responseBody);
    }
}